const buildTree = (data: any) => {
  // 创建一个映射表来存储所有节点，以便快速查找
  const map = new Map();
  data.forEach((item: any) => {
    map.set(item._id.toString(), {
      ...item._doc,
      _id: item._id.toString(),
      children: [],
    });
  });

  // 创建根节点数组
  const tree = [] as any;
  data.forEach((item: any) => {
    if (item.parentId === "0") {
      // 如果是根节点，则直接添加到树中
      tree.push(map.get(item._id.toString()));
    } else {
      // 否则找到其父节点并添加为子节点
      const parent = map.get(item.parentId);

      if (parent) {
        parent.children.push(map.get(item._id.toString()));
      }
    }
  });

  // 递归函数：为每个节点添加 ancestors 属性
  const addAncestors = (node: any, ancestors = []) => {
    if (ancestors.length !== 0) {
      node.ancestors = [...ancestors, node.name];
    }

    for (const child of node.children) {
      addAncestors(child, [...ancestors, node.name] as any);
    }
  };

  // 对每个根节点调用 addAncestors
  tree.forEach((root: any) => addAncestors(root));

  return tree;
};

export default buildTree;
